﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using SubSonic.Sugar;
using System.Security;
using MediaMonitor.Common;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net;
using System.Configuration;
using Telerik.Web.UI;
using System.Collections;

namespace MediaMonitor.Admin
{
    public partial class User_Mgmt_NewsAlert : Adex.BasePage
    {
        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        private static string AppName = ConfigurationManager.AppSettings["AppName"].ToString();
        private static string AdminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString();
        private iTextSharp.text.Font PDF_FONT_DEFAULT;
        private iTextSharp.text.Font PDF_FONT_TH;
        private iTextSharp.text.Font PDF_FONT_BOLD;
        private iTextSharp.text.Font PDF_FONT_GRAY;
        private iTextSharp.text.Font PDF_FONT_LIGHTGRAY;
        private iTextSharp.text.Font PDF_FONT_TITLE;
        private iTextSharp.text.Font PDF_FONT_HEADING;
        private iTextSharp.text.Font PDF_FONT_HEADING_GRAY;
        private iTextSharp.text.Font PDF_FONT_BIG;
        private iTextSharp.text.Font PDF_FONT_BIG_BOLD;
        private iTextSharp.text.Font PDF_FONT_NAV;
        private iTextSharp.text.Font PDF_FONT_GridElements;

        protected void Page_Init(object sender, EventArgs e)
        {
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            string fontpath = Server.MapPath("../");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "/Fonts/KOKILA.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font Kokila = new Font(customfont, 44, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_TITLE = Kokila;
            BaseFont customfontarial = BaseFont.CreateFont(fontpath + "/Fonts/ARIAL.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font ARIAL = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIAL11 = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIALNORMAL11 = new Font(customfontarial, 11, Font.NORMAL, BaseColor.BLACK);
            Font ARIALNORMAL7 = new Font(customfontarial, 7, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_DEFAULT = ARIALNORMAL11;
            PDF_FONT_TH = ARIAL;
            PDF_FONT_BOLD = ARIAL11;
            PDF_FONT_GRAY = new Font(bf, 14, Font.NORMAL, BaseColor.DARK_GRAY);
            PDF_FONT_LIGHTGRAY = new Font(bf, 15, Font.NORMAL, new BaseColor(System.Drawing.Color.FromArgb(141, 141, 141)));
            PDF_FONT_HEADING = new Font(bf, 16, Font.BOLD, BaseColor.WHITE);
            PDF_FONT_HEADING_GRAY = new Font(bf, 18, Font.BOLD, BaseColor.GRAY);
            PDF_FONT_BIG = new Font(bf, 14, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_BIG_BOLD = new Font(bf, 14, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_NAV = new Font(bf, 14, Font.BOLD, BaseColor.RED);
            PDF_FONT_GridElements = ARIALNORMAL7;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);
                SetCalendarDates();
                hdnCompanyID.Value = Utility.GetRequestedVal("cid", "0");
            }
        }
        private void SetCalendarDates()
        {
            DataTable dt = TblNewsAlert.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = Utility.ToDateTime(dr["RFDate"]);
                d1.IsDisabled = false;
                d1.IsSelectable = true;
                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;
                calS.SpecialDays.Add(d1);
                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = Utility.ToDateTime(dr["RFDate"]);
                d2.IsDisabled = false;
                d2.IsSelectable = true;
                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;
                calE.SpecialDays.Add(d2);
            }
        }
        protected void radGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            DataTable dt;
            if (hdnCompanyID.Value == "0")
                dt = VSiteUser.Query().SetSelectList("*").WHERE("RoleName", "user").ORDER_BY("UserName").ExecuteDataSet().Tables[0];
            else
                dt = VSiteUser.Query().SetSelectList("*").WHERE("CompanyCode", hdnCompanyID.Value).ORDER_BY("UserName").ExecuteDataSet().Tables[0];
            radGrid.DataSource = dt;
        }
        protected void btnSend_Clicked(object sender, EventArgs e)
        {

            GridItem itm;

            string script;

            IDisposable disposable;

            bool flag;

            bool flag1;

            ReportFuncs rep = new ReportFuncs();

            DataTable dt = rep.GetUserIDAndRolle(this.Session["UserID"].ToString());

            string Role = dt.Rows[0][2].ToString();

            DateTime selectedDate = this.calS.SelectedDate;

            bool tmp1 = DateTime.TryParse(selectedDate.ToShortDateString(), out this.sDate);

            selectedDate = this.calE.SelectedDate;

            bool tmp2 = DateTime.TryParse(selectedDate.ToShortDateString(), out this.eDate);

            string selEmail = string.Empty;

            bool dateTime = !(this.sDate < Utility.ToDateTime("01/01/2000"));

            if (!dateTime)
            {

                this.sDate = Utility.ToDateTime("01/01/2000");

            }

            dateTime = !(this.eDate < Utility.ToDateTime("01/01/2000"));

            if (!dateTime)
            {

                this.eDate = Utility.ToDateTime("01/01/2000");

            }

            IEnumerator enumerator = this.radGrid.SelectedItems.GetEnumerator();

            try
            {

                while (true)
                {

                    dateTime = enumerator.MoveNext();

                    if (!dateTime)
                    {

                        break;

                    }

                    itm = (GridItem)enumerator.Current;

                    selEmail = string.Concat(selEmail, this.radGrid.MasterTableView.DataKeyValues[itm.ItemIndex]["Email"].ToString(), ",");

                }

            }

            finally
            {

                disposable = enumerator as IDisposable;

                dateTime = disposable == null;

                if (!dateTime)
                {

                    disposable.Dispose();

                }

            }

            flag = (this.sDate.ToString() == "01/01/2000 12:00:00 AM" ? true : !(this.eDate.ToString() != "01/01/2000 12:00:00 AM"));

            dateTime = flag;

            if (dateTime)
            {

                script = "alert(\"Please select date first!\");";

                System.Web.UI.ScriptManager.RegisterStartupScript(this, base.GetType(), "ServerControlScript", script, true);

            }

            else
            {

                dateTime = !(selEmail == string.Empty);

                if (dateTime)
                {

                    flag1 = (Role == "advanced user" ? false : !(Role == "admin"));

                    dateTime = flag1;

                    if (dateTime)
                    {

                        script = "alert(\"You have no authority to send mail!\");";

                        System.Web.UI.ScriptManager.RegisterStartupScript(this, base.GetType(), "ServerControlScript", script, true);

                    }

                    else
                    {

                        enumerator = this.radGrid.SelectedItems.GetEnumerator();

                        try
                        {

                            while (true)
                            {

                                dateTime = enumerator.MoveNext();

                                if (!dateTime)
                                {

                                    break;

                                }

                                itm = (GridItem)enumerator.Current;

                                string import = string.Empty;

                                CheckBoxList checkBoxList = (CheckBoxList)itm.FindControl("chkListImportant");

                                IEnumerator enumerator1 = checkBoxList.Items.GetEnumerator();

                                try
                                {

                                    while (true)
                                    {

                                        dateTime = enumerator1.MoveNext();

                                        if (!dateTime)
                                        {

                                            break;

                                        }

                                     System.Web.UI.WebControls.ListItem itms = (System.Web.UI.WebControls.ListItem)enumerator1.Current;

                                        dateTime = !itms.Selected;

                                        if (!dateTime)
                                        {

                                            import = string.Concat(import, itms.Text, ",");

                                        }

                                    }

                                }

                                finally
                                {

                                    disposable = enumerator1 as IDisposable;

                                    dateTime = disposable == null;

                                    if (!dateTime)
                                    {

                                        disposable.Dispose();

                                    }

                                }

                                char[] chrArray = new char[] { ',' };

                                string mailBody = this.GetInformationOfNewsAlertByCompany(this.radGrid.MasterTableView.DataKeyValues[itm.ItemIndex]["CompanyName"].ToString(), import.TrimEnd(chrArray),chkNewalert.Checked);

                                this.SendMail(this.radGrid.MasterTableView.DataKeyValues[itm.ItemIndex]["Email"].ToString(), mailBody);

                            }

                        }

                        finally
                        {

                            disposable = enumerator as IDisposable;

                            dateTime = disposable == null;

                            if (!dateTime)
                            {

                                disposable.Dispose();

                            }

                        }

                    }

                }

                else
                {

                    script = "alert(\"Please select atleast one user!\");";

                    System.Web.UI.ScriptManager.RegisterStartupScript(this, base.GetType(), "ServerControlScript", script, true);

                }

            }

        }
        public string GetInformationOfNewsAlertByCompany(string Company, string Important,bool newsalert)
        {
                string url = String.Empty;
                url = "http://mediamonitor.do/users/NewsAlert.aspx";
                   if (newsalert)
                   {
                       url = "http://www.newsalert.do/ShareNews.aspx?Code=";
                   }
              
                string Mailbody = "<table cellspacing='0' border='1' style='width:100%;table-layout:fixed;empty-cells:show;font-size:12px;font-family: Verdana;' id='ctl00' rules='all'><colgroup><col style='width:30px'><col></colgroup>";
                Mailbody += "<thead><tr>";
                Mailbody += "<th style='-moz-border-bottom-colors: none;-moz-border-left-colors: none;-moz-border-right-colors: none;-moz-border-top-colors: none;border-color: -moz-use-text-color -moz-use-text-color #828282;border-image: none;border-style: none none solid;border-width: 0 0 1px;color: White;font-weight: normal;padding-bottom: 4px;padding-top: 5px;text-align: left;background-color:#7ABC1F' scope='col'>&nbsp;</th>";
                Mailbody += "<th style='text-align: center; cursor: move;-moz-border-bottom-colors: none;-moz-border-left-colors: none;-moz-border-right-colors: none;-moz-border-top-colors: none;border-color: -moz-use-text-color -moz-use-text-color #828282;border-image: none;border-style: none none solid;border-width: 0 0 1px;font-weight: normal;padding-bottom: 4px;padding-top: 5px;text-align: center;background-color:#7ABC1F' scope='col' title='Drag to group or reorder'>News &amp; Alert</th>";
                Mailbody += "</tr></thead>";
                //Mailbody += "<tfoot>";
                //Mailbody += "<tr style='color:AliceBlue;border-width:1px;border-style:solid;font-size:Smaller;font-weight:bold;'>";
                //Mailbody += "<td>&nbsp;</td><td>&nbsp;</td>";
                //Mailbody += "</tr></tfoot>";

                DataTable dt = SPs.GetInformationOfNewsAlertByCompany(Company, Important).GetDataSet().Tables[0];

                int i = 0;

                while (true)
                {

                    bool count = i < dt.Rows.Count;

                    if (!count)
                    {

                        break;

                    }

                    string color = "";

                    string str = Utility.IsNullStr(dt.Rows[i]["Calification"]);

                    if (str != null)
                    {

                        if (str == "Neutra")
                        {

                            color = "#3F47CC";

                        }

                        else
                        {

                            if (str == "Positiva")
                            {

                                color = "#319A00";

                            }

                            else
                            {

                                if (str == "Negativa")
                                {

                                    color = "#FB0200";

                                }

                            }

                        }

                    }

                    string Pagina = "";

                    count = !(dt.Rows[i]["MediaTypeName"].ToString() == "Press");

                    Pagina = (count ? "Hora" : "Pagina");

                    object obj = Mailbody;

                    object[] item = new object[] { obj, " <tbody><tr style='border-width:1px;border-style:solid;font-size:Smaller;' id='ctl00_0'><td style='width:30px;'><img alt='TV' src='http://mediamonitor.do/images/media/" + dt.Rows[i]["MediaTypeName"].ToString() + ".png'></td><td><img alt='TV' src='http://mediamonitor.do/images/media/" + dt.Rows[i]["Calification"].ToString() + ".png'>&nbsp;&nbsp;&nbsp; <b style='color: ", color, ";'>", dt.Rows[i]["Title"], "</b><br/><br/>" };

                    Mailbody = string.Concat(item);

                    DateTime dateTime = Convert.ToDateTime(dt.Rows[i]["RFDate"]);

                    Mailbody = string.Concat(Mailbody, "<b style='color: #cd9035'>Fecha:</b><b style='color: #253e5c; font-weight: normal;'>", dateTime.ToShortDateString(), "</b>&nbsp;&nbsp;&nbsp;");

                    string str1 = Mailbody;

                    string[] strArrays = new string[] { str1, " <b style='color: #cd9035'>", Pagina, "</b><b style='color: #253e5c; font-weight: normal;'>", dt.Rows[i]["PageorHour"].ToString(), "</b>&nbsp;&nbsp;&nbsp;" };

                    Mailbody = string.Concat(strArrays);

                    Mailbody = string.Concat(Mailbody, " <b style='color: #cd9035'>Duracion:</b><b style='color: #253e5c; font-weight: normal;'>", Utility.IsNullStr(dt.Rows[i]["Duration"]), "</b>&nbsp;&nbsp;&nbsp;");

                    Mailbody = string.Concat(Mailbody, " <b style='color: #cd9035'>Medio:</b><b style='color: #253e5c; font-weight: normal;'>", Utility.IsNullStr(dt.Rows[i]["MediaDescription"]), "</b>&nbsp;&nbsp;&nbsp;");

                    Mailbody = string.Concat(Mailbody, " <b style='color: #cd9035'>Seccion:</b><b style='color: #253e5c; font-weight: normal;'>", Utility.IsNullStr(dt.Rows[i]["SectionDescription"]), "</b>&nbsp;&nbsp;&nbsp;");

                    Mailbody = string.Concat(Mailbody, " <b style='color: #cd9035'>Calificación:</b><b style='color: #253e5c; font-weight: normal;'>", Utility.IsNullStr(dt.Rows[i]["Calification"]), "</b>&nbsp;&nbsp;&nbsp;");

                    Mailbody = string.Concat(Mailbody, " <b style='color: #cd9035'>Importancia:</b><b style='color: #253e5c; font-weight: normal;'>", Utility.IsNullStr(dt.Rows[i]["Important"]), "</b>&nbsp;&nbsp;&nbsp;");

                    Mailbody = string.Concat(Mailbody, "<br/><br/><p style='color: #27436a; font-size: 10px;'>", Utility.IsNullStr(dt.Rows[i]["NewsSummary"]), " </p>");
                    if (newsalert)
                    Mailbody = string.Concat(Mailbody, " <p style='text-align: center'><a style='color: #722932;' href='"+url+Utility.IsNullStr(dt.Rows[i]["ID"])+"' target='_blank'>Read More</a></p></td></tr></tbody>");
                    else
                        Mailbody = string.Concat(Mailbody, " <p style='text-align: center'><a style='color: #722932;' href='" + url + "' target='_blank'>Read More</a></p></td></tr></tbody>");
                    i++;

                }

                Mailbody = string.Concat(Mailbody, "<table>");

                string str2 = Mailbody;

                return str2;
            
        }
       
        private void SendMail(String Users,string message)
        {
            String msg = "Estimado Usuario,<br/><br/> <br/>Hemos cargado nuevas alertas y noticias de su interés, a continuación un resumen de ellas:<br/><br/>";
            msg = msg + message;
            String title = "Alertas y noticias Nielsen IBOPE RD";
            String toAccount = Users;
            //String toAccount = "niteshguleria@nascenture.com";
            String MyHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            String MySMTPPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            String MySMTPSSL = ConfigurationManager.AppSettings["SMTPSSL"].ToString();
            String fromAddr = AdminEmail;   //Email Address of Sender
            MailMessage smtpMssg = new MailMessage();
            smtpMssg.From = new MailAddress(fromAddr);
            if (toAccount.Contains(","))
            {
                string[] tos = toAccount.Split(',');
                for (int i = 0; i < tos.Length; i++)
                {
                    if (tos[i] == "," || tos[i] == "")
                    {
                    }
                    else
                    {
                        smtpMssg.To.Add(new MailAddress(tos[i].Replace(",","")));
                    }
                }
            }
            else
            {
                smtpMssg.To.Add(new MailAddress(toAccount));
            }
            smtpMssg.Subject = title;
            smtpMssg.Body = msg;
            smtpMssg.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort));
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (MySMTPSSL == "true")
            {
                smtpClient.EnableSsl = true;
            }

            try
            {
                smtpClient.Send(smtpMssg);
            }
            catch (Exception ex)
            {
                throw new Exception("Email not sent | Reason: [" + ex.Message + "]");
            }
        }
    }
}